<?php
require_once('Kbs/Controller/Action.php');

class Admin_UserController extends Kbs_Controller_Action
{
    public function indexAction()
    {
        $form = new Zend_Form();
        $captcha = $this->createCaptcha();
        $form->addElement($captcha);
        $form->addElement($form->createElement('submit', 'submit'));

        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();

            $captchaData = $this->getRequest()->getPost('captcha');
            $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaData['id']);
            $captchaIterator = $captchaSession->getIterator();

            if ($form->isValid($formData) and $captchaData['input'] == $captchaIterator['word']) {
                echo 'pass';
            } else {
                echo 'error';
                $form->populate($formData);
            }
        }

        $this->view->captchaImageUrl = $captcha->getCaptcha()->getImgUrl()
                                     . $captcha->getCaptcha()->getId()
                                     . $captcha->getCaptcha()->getSuffix();

        $this->view->formLogin = $form->render();
    }

    public function ajaxAction()
    {
        $captcha = $this->createCaptcha()->getCaptcha();
        $captcha->generate();
        echo $captcha->getImgUrl() . $captcha->getId() . $captcha->getSuffix();
        die;
    }

    public function createCaptcha()
    {
        $decorators = array(
            array('HtmlTag', array('tag' => 'div',
                                   'id' => 'captchaId',
                                   'onclick' => 'changeImage()'))
        );

        $form = new Zend_Form();

        $captcha = $form->createElement('captcha', 'captcha', array(
            'captcha' => array(
                'captcha' => 'Image',
                'wordLen' => 6,
                'fontsize' => 20,
                'width' => 200,
                'height' => 100,
                'dotNoiseLevel' => 2,
                'timeout' => 300,
                'font' => 'fonts/faktos/Faktos.ttf',
                'imgDir' => './img/captcha/',
                'imgUrl' => '/img/captcha/',
                'gcFreq' => '2',
                'expiration' => '15',
            ),
            'decorators' => $decorators
        ));

        return $captcha;
    }
}